<template>
  <BasicModal
    v-bind="$attrs"
    :width="modalWidth"
    @register="registerModal"
    title="添加"
    @ok="handleOK"
  >
    <BasicForm @register="registerFormPeople" />
    <MatchingResult ref="childComponentRef"></MatchingResult>
  </BasicModal>
</template>

<script lang="ts" setup>
  import { ref, computed, onMounted, watch } from 'vue';
  import { BasicModal, useModalInner } from '@/components/Modal';
  import { BasicForm, useForm } from '@/components/Form';
  import { message } from 'ant-design-vue';
  import { SubcreateTaskAPI } from '@/api/demo/InformationMatching';
  import { getAudiencesListAPI } from '@/api/demo/template';
  import MatchingResult from '../.././Components/matchingResult/index.vue';
  import { useI18n } from "@/hooks/web/useI18n";

  const { t } = useI18n();
  const accountFormSchemPeople = ref([
    {
      field: 'templateId',
      component: 'ApiSelect',
      label: '广告受众模板',
      defaultValue: '',
      colProps: {
        span: 24,
      },
      componentProps: {
        api: getAudiencesListAPI, // 指定接口函数
        resultField: 'data', // 接口返回的数据字段名
        labelField: 'remark', // 选项显示的标签字段名
        valueField: 'id', // 选项的值字段名
        placeholder: '请选择模板', // 添加提示文本
        onChange: (value) => {
          // 触发 fetchTemplateDetail 方法
          fetchTemplateDetail(value);
        },
      },
    },
    {
      field: 'title',
      component: 'Input',
      label: t('sys.informaionMatchaing.columns.title'),
      defaultValue: '',
      colProps: {
        span: 24,
      },
      rules: [{ required: true }],
    },
    {
      field: 'content',
      component: 'InputTextArea',
      label: t('sys.configuration.describe'),
      defaultValue: '',
      colProps: {
        span: 24,
      },
      componentProps: {
        rows: 3, // 设置文本域的行数
      },
      rules: [{ required: true }],
    },
    {
      field: 'district',
      component: 'Input',
      label:  t('sys.informaionMatchaing.columns.district'),
      defaultValue: '',
      rules: [{ required: true }],
    },

    // {
    //   field: 'age',
    //   component: 'Input',
    //   label:  t('sys.informaionMatchaing.columns.age'),
    //   defaultValue: '',
    //   rules: [{ required: true }],
    // },
    // {
    //   field: 'gender',
    //   component: 'Input',
    //   label:  t('sys.informaionMatchaing.columns.gender'),
    //   defaultValue: '',
    //   rules: [{ required: true }],
    // },
    {
      field: 'audience',
      component: 'Input',
      label:  t('sys.informaionMatchaing.columns.audience'),
      defaultValue: '',
      rules: [{ required: true }],
    },
    {
      field: 'interest',
      component: 'InputTextArea',
      label:  t('sys.informaionMatchaing.columns.interest'),
      defaultValue: '',
      componentProps: {
        rows: 3, // 设置文本域的行数
      },
      rules: [{ required: true }],
    },
  ]);
  const emit = defineEmits(['success']);
  defineOptions({ name: 'AccountModal' });

  const isUpdate = ref(true);
  const rowId = ref('');
  const modalWidth = ref('50%');
  const templateList = ref<any[]>([]);
  const templateId = ref('');

  const [registerFormPeople, { getFieldsValue: getFieldsValuePeople, setFieldsValue }] = useForm({
    labelWidth: 100,
    baseColProps: { span: 24 },
    schemas: accountFormSchemPeople,
    showActionButtonGroup: false,
  });

  const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
    setModalProps({ confirmLoading: false });
    isUpdate.value = !!data?.isUpdate;
  });

  // 定义一个 ref 来引用子组件
  const childComponentRef = ref(null);

  onMounted(async () => {
    try {
      const response = await getAudiencesListAPI();
      templateList.value = response.data; // 假设接口返回的数据结构为 { data: [] }
    } catch (error) {
      console.error('获取模板列表失败', error);
    }
  });

  watch(
    () => templateId.value,
    async (newId) => {
      if (newId) {
        await fetchTemplateDetail(newId);
      }
    },
  );

  async function fetchTemplateDetail(id: string) {
    try {
      const detail = templateList.value.find((item) => item.id === id);
      if (detail) {
        setFieldsValue({
          title: detail.title,
          content: detail.content,
          district: detail.district,
          age: detail.age,
          gender: detail.gender,
          audience: detail.audience,
          interest: detail.interest,
        });
      }
    } catch (error) {
      console.error('获取模板详情失败', error);
    }
  }

  async function handleOK() {
    setModalProps({ confirmLoading: true });

    if (childComponentRef.value) {
      const formattedLinksValue = childComponentRef.value.getFormattedLinks();
      // 将 formattedLinksValue 根据逗号分隔成数组
      const linksArray = formattedLinksValue.split(',').map((link) => link.trim());
      const params = { ...getFieldsValuePeople(), links: linksArray };
      const data = await SubcreateTaskAPI(params);
      emit('success', data);
      closeModal();
    } else {
      message.error('子组件未初始化');
    }

    setModalProps({ confirmLoading: false });
  }
</script>
